package com.jboost.modules.area.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jboost.common.api.vo.Result;
import com.jboost.common.aspect.annotation.AutoLog;
import com.jboost.common.system.query.QueryGenerator;
import com.jboost.common.util.RedisUtil;
import com.jboost.modules.area.constant.JboostAreaConstant;
import com.jboost.modules.area.entity.JboostArea;
import com.jboost.modules.area.model.JboostAreaTreeModel;
import com.jboost.modules.area.service.JboostAreaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: area
 * @Author: cxn
 * @Date: 2021-05-11
 * @Version: V1.0
 */
@Api(tags = "地址区域")
@RestController
@RequestMapping("/area")
@Slf4j
public class JboostAreaController {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private JboostAreaService areaService;

    /**
     * 分页列表查询
     *
     * @param area
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "area-分页列表查询")
//    @ApiOperation(value = "area-分页列表查询", notes = "area-分页列表查询")
    @GetMapping(value = "/pageList")
    public Result<?> queryPageList(JboostArea area,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<JboostArea> queryWrapper = QueryGenerator.initQueryWrapper(area, req.getParameterMap());
        Page<JboostArea> page = new Page<JboostArea>(pageNo, pageSize);
        IPage<JboostArea> pageList = areaService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @AutoLog(value = "area-树列表查询")
    @ApiOperation(value = "area-树列表查询", notes = "area-树列表查询")
    @GetMapping(value = "/treeList")
    public Result<?> queryTreeList() {
//		LambdaQueryWrapper<Area> queryWrapper = new QueryWrapper<Area>().lambda();
//		queryWrapper.eq(FileType::getFileId,attach.getFileId());
        try {
            Object obj = redisUtil.get(JboostAreaConstant.AREA_TREE_CACHE);
            if (null != obj) {
                return Result.OK(obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<JboostArea> list = areaService.list();
        List<JboostAreaTreeModel> treeList = new ArrayList<>();
        if (null != list && list.size() > 0) {
            getTreeModelList(treeList, list, null);
            redisUtil.set(JboostAreaConstant.AREA_TREE_CACHE, treeList);
        }
        return Result.OK(treeList);
    }

    @AutoLog(value = "area-清缓存")
//    @ApiOperation(value = "area-清缓存", notes = "area-清缓存")
    @GetMapping(value = "/clearTreeCache")
    public Result<?> clearTreeCache() {
        redisUtil.del(JboostAreaConstant.AREA_TREE_CACHE);
        redisUtil.del(JboostAreaConstant.AREA_LIST_CACHE);
        return Result.OK();
    }

    /**
     * 添加
     *
     * @param area
     * @return
     */
    @AutoLog(value = "area-添加")
//    @ApiOperation(value = "area-添加", notes = "area-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody JboostArea area) {


        //判断上级是不是存在
        areaService.save(area);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param cscCategory
     * @return
     */
    @AutoLog(value = "area-编辑")
//    @ApiOperation(value = "area-编辑", notes = "area-编辑")
    @PutMapping(value = "/edit/{id}")
    public Result<?> edit(@RequestBody JboostArea cscCategory, @PathVariable(name = "id", required = true) String id) {
        areaService.updateById(cscCategory);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "area-通过id删除")
//    @ApiOperation(value = "area-通过id删除", notes = "area-通过id删除")
    @DeleteMapping(value = "/delete/{id}")
    public Result<?> delete(@PathVariable(name = "id", required = true) String id) {
        JboostArea cscCategory = areaService.getById(id);
        if (null == cscCategory) {
            return Result.error("找不到对应的分类！");
        }
        //判断是否有下级或关联产品，此时不能删除

        //删除
        areaService.removeById(id);

        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "area-批量删除")
//    @ApiOperation(value = "area-批量删除", notes = "area-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.areaService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "area-通过id查询")
//    @ApiOperation(value = "area-通过id查询", notes = "area-通过id查询")
    @GetMapping(value = "/info/{id}")
    public Result<?> queryById(@PathVariable(name = "id", required = true) String id) {
        JboostArea cscCategory = areaService.getById(id);
        if (cscCategory == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(cscCategory);
    }


    private void getTreeModelList(List<JboostAreaTreeModel> treeList, List<JboostArea> metaList, JboostAreaTreeModel temp) {
        for (JboostArea area : metaList) {
            String tempPCode = area.getPCode();
            JboostAreaTreeModel tree = new JboostAreaTreeModel(area);
            if (temp == null && "86".equals(tempPCode)) {
                treeList.add(tree);
                if (tree.getHasChild()) {
                    getTreeModelList(treeList, metaList, tree);
                }
            } else if (temp != null && tempPCode != null && tempPCode.equals(temp.getCode())) {
                temp.getChildren().add(tree);
                if (tree.getHasChild()) {
                    getTreeModelList(treeList, metaList, tree);
                }
            }

        }
    }


    @AutoLog(value = "area-通过pcode查询")
//    @ApiOperation(value = "area-通过pcode查询", notes = "area-通过pcode查询")
    @GetMapping(value = "/queryByPcode/{pcode}")
    public Result<?> queryByPcode(@PathVariable(name = "pcode", required = true) String pcode) {
        QueryWrapper<JboostArea> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("p_code", pcode);
        List<JboostArea> areaList = areaService.list(queryWrapper);
        if (StringUtils.isEmpty(areaList)) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(areaList);
    }
}
